package com.panghl.config;

import com.mysql.cj.jdbc.MysqlXADataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Author panghl
 * @Date 2022/2/17
 * @Description TODO
 **/
@Configuration
@MapperScan(basePackages = "com.panghl.test01", sqlSessionFactoryRef = "test01SqlSessionFactory")
public class DataSource1Config {

    /**
     * 配置test01数据库
     *
     * @return
     */
    @Bean(name = "test01DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test01")
    @Primary
    public DataSource test01DataSource() throws SQLException {
        return DataSourceBuilder.create().build();
    }

    /**
     * test01 sql会话工厂
     */
    @Bean(name = "test01SqlSessionFactory")
    public SqlSessionFactory test01SqlSessionFactory(@Qualifier("test01DataSource") DataSource test01DataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(test01DataSource);
        //bean.setMapperLocations(
        //        new PathMatchingResourcePatternResolver().getResource("classpath:mapping/test/*Mapper.xml")
        //);
        return bean.getObject();
    }

    /**
     * test01 事务管理器
     */
    @Bean(name = "test01DataSourceTransactionManager")
    public DataSourceTransactionManager test01DataSourceTransactionManager(@Qualifier("test01DataSource") DataSource test01DataSource) {
        return new DataSourceTransactionManager(test01DataSource);
    }

    @Bean(name = "test01SqlSessionTemplate")
    public SqlSessionTemplate test01SqlSessionTemplate(@Qualifier("test01SqlSessionFactory") SqlSessionFactory test01SqlSessionFactory) {
        return new SqlSessionTemplate(test01SqlSessionFactory);
    }

}
